<?php
/**
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php
*
* This is Midori, the command line utility of akaikiwi.
* For more information check the documentation
* Or run the script with -h argument
*/

class Midori {
	function __construct() {
		if(count($_SERVER['argv']) <= 2) {
			echo $this->get_help();
			return;
		}

		$command = $_SERVER['argv'][1];
		switch ($command) {
			case 'crud':
				$this->create_crud();
				break;
			default:
				echo $this->get_help();
				break;
		}
	}

	private function get_help() {
		return <<<EOD

Midori
Command line shell for akaikiwi

COMMANDS

[crud]
creates a new CRUD with the given table name

usage:	crud my_table
options:
	-c <name>	the name of the controller
EOD;
	}

	private function create_crud() {
		echo "\nCreating CRUD...\n";

		if(count($_SERVER['argv']) < 3 || strpos($_SERVER['argv'][2], '-') !== FALSE) {
			echo $this->get_help();
			return;
		}

		$table_name = $_SERVER['argv'][2];
		$base = str_replace('\\', '/', __DIR__);
		define('inside', TRUE);
		include_once $base.'/../libs/sys/AkaikiwiException.php';
		include_once $base.'/../libs/Config.php';
		$config = new Config();
		include_once $base.'/../libs/vendor/redbean/rb.php';
		$str = $config->get_item('dbRBConnection');
		$str = explode('-', $str);
		$conn = $str[0];
		if(strpos($conn, 'sqlite') !== FALSE) {
			R::setup($conn);
		} else {
			R::setup($conn, $str[1], $str[2]);
		}
		R::freeze();

		try {
			$cols = R::$writer->getColumns($table_name);
		} catch(Exception $e) {
			echo "\n" . $e->getMessage();
			return;
		}

		array_shift($cols);

		$controller_name = $table_name;
		if(in_array('-c', $_SERVER['argv'])) {
			$controller_name = $_SERVER['argv'][array_search('-c', $_SERVER['argv']) + 1];
		}

		$controller = file_get_contents($base.'/rb_crud/controller');
		$controller = str_replace('{table_name}', $table_name, $controller);
		$controller = str_replace('{class_name}', ucfirst($controller_name), $controller);
		$controller = str_replace('{name}', $controller_name, $controller);
		$controller = str_replace('{csv_fields}', implode(',', array_keys($cols)), $controller);

		$path_controller = $base . '/../../app/controllers/'.ucfirst($controller_name).'.php';
		if(file_exists($path_controller)) {
			echo "\nError: A controller with the given name already exists\n$path_controller";
			return;
		}

		// Model
		$model = file_get_contents($base.'/rb_crud/model');
		$model = str_replace('{table_name}', ucfirst($table_name), $model);
		$model_path = $base . '/../../app/models/Model_'.ucfirst($table_name).'.php';
		if(file_exists($model_path)) {
			echo "\nError: A model with the given name already exists\n$model_path";
			return;
		}

		// Views

		// create
		$create = file_get_contents($base.'/rb_crud/create');
		$tr = NULL;
		foreach($cols as $name => $val) {
			$form_type = 'form_input';
			if($val == 'text') {
				$form_type = 'form_textarea';
			}
			$tr .= '<tr><td>'.ucfirst($name).'</td><td><?php echo '.$form_type.'("'.$name.'"); ?></td></tr>';
		}
		$create = str_replace('{tr}', $tr, $create);
		$create = str_replace('{controller_name}', $controller_name, $create);
		$create_path = $base . '/../../app/views/'.$controller_name.'/create.php';
		if(file_exists($create_path)) {
			echo "\nError: A view with the given name already exists\n$create_path";
			return;
		}

		// create_created
		$create_created = file_get_contents($base.'/rb_crud/create_created');
		$create_created = str_replace('{controller_name}', $controller_name, $create_created);
		$create_created_path = $base . '/../../app/views/'.$controller_name.'/create_created.php';
		if(file_exists($create_created_path)) {
			echo "\nError: A view with the given name already exists\n$create_created_path";
			return;
		}

		// delete
		$delete = file_get_contents($base.'/rb_crud/delete');
		$delete = str_replace('{controller_name}', $controller_name, $delete);
		$delete_path = $base . '/../../app/views/'.$controller_name.'/delete.php';
		if(file_exists($delete_path)) {
			echo "\nError: A view with the given name already exists\n$delete_path";
			return;
		}

		// delete_error
		$delete_error = file_get_contents($base.'/rb_crud/delete_error');
		$delete_error = str_replace('{controller_name}', $controller_name, $delete_error);
		$delete_error_path = $base . '/../../app/views/'.$controller_name.'/delete_error.php';
		if(file_exists($delete_error_path)) {
			echo "\nError: A view with the given name already exists\n$delete_error_path";
			return;
		}

		// index
		$first_field = NULL;
		foreach($cols as $k => $v) {
			$first_field = $k;
			break;
		}

		$index = file_get_contents($base.'/rb_crud/index');
		$index = str_replace('{controller_name}', $controller_name, $index);
		$index = str_replace('{first_field}', $first_field, $index);
		$index_path = $base . '/../../app/views/'.$controller_name.'/index.php';
		if(file_exists($index_path)) {
			echo "\nError: A view with the given name already exists\n$index_path";
			return;
		}

		// read
		$read = file_get_contents($base.'/rb_crud/read');
		$tr = NULL;
		foreach($cols as $name => $val) {
			$tr .= '<tr><td>'.ucfirst($name).'</td><td><?php echo $data[\'item\']->'.$name.'; ?></td></tr>';
		}
		$read = str_replace('{tr}', $tr, $read);
		$read = str_replace('{controller_name}', $controller_name, $read);
		$read_path = $base . '/../../app/views/'.$controller_name.'/read.php';
		if(file_exists($read_path)) {
			echo "\nError: A view with the given name already exists\n$read_path";
			return;
		}

		// read_error
		$read_error = file_get_contents($base.'/rb_crud/read_error');
		$read_error = str_replace('{controller_name}', $controller_name, $read_error);
		$read_error_path = $base . '/../../app/views/'.$controller_name.'/read_error.php';
		if(file_exists($read_error_path)) {
			echo "\nError: A view with the given name already exists\n$read_error_path";
			return;
		}

		// update
		$update = file_get_contents($base.'/rb_crud/update');
		$tr = NULL;
		foreach($cols as $name => $val) {
			$form_type = 'form_input';
			if($val == 'text') {
				$form_type = 'form_textarea';
			}
			$tr .= '<tr><td>'.ucfirst($name).'</td><td><?php echo '.$form_type.'(\''.$name.'\', NULL, $data[\'item\']->'.$name.'); ?></td></tr>';
		}
		$update = str_replace('{tr}', $tr, $update);
		$update = str_replace('{controller_name}', $controller_name, $update);
		$update_path = $base . '/../../app/views/'.$controller_name.'/update.php';
		if(file_exists($update_path)) {
			echo "\nError: A view with the given name already exists\n$update_path";
			return;
		}

		// update_error
		$update_error = file_get_contents($base.'/rb_crud/update_error');
		$update_error = str_replace('{controller_name}', $controller_name, $update_error);
		$update_error_path = $base . '/../../app/views/'.$controller_name.'/update_error.php';
		if(file_exists($update_error_path)) {
			echo "\nError: A view with the given name already exists\n$update_error_path";
			return;
		}

		// update_updated
		$update_updated = file_get_contents($base.'/rb_crud/update_updated');
		$update_updated = str_replace('{controller_name}', $controller_name, $update_updated);
		$update_updated_path = $base . '/../../app/views/'.$controller_name.'/update_updated.php';
		if(file_exists($update_updated_path)) {
			echo "\nError: A view with the given name already exists\n$update_updated_path";
			return;
		}

		echo "\nAll's good! Creating files...";

		mkdir($base . '/../../app/views/' . $controller_name, 0777, TRUE);
		mkdir($base . '/../../app/controllers');
		mkdir($base . '/../../app/models');

		file_put_contents($path_controller, $controller);
		file_put_contents($model_path, $model);
		file_put_contents($create_path, $create);
		file_put_contents($create_created_path, $create_created);
		file_put_contents($delete_path, $delete);
		file_put_contents($delete_error_path, $delete_error);
		file_put_contents($index_path, $index);
		file_put_contents($read_path, $read);
		file_put_contents($read_error_path, $read_error);
		file_put_contents($update_path, $update);
		file_put_contents($update_error_path, $update_error);
		file_put_contents($update_updated_path, $update_updated);

		echo "\nAll files created!\n";
	}
}

new Midori();
